import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Dictionary } from '../entity/dictionary.entity';
import { DictionaryItem } from '../entity/dictionary-item.entity';

@Injectable()
export class DictionaryService {
  constructor(
    @InjectRepository(Dictionary)
    private dictionaryRepository: Repository<Dictionary>,
    @InjectRepository(DictionaryItem)
    private itemRepository: Repository<DictionaryItem>
  ) {}

  async createDictionary(type: string, name: string,description:string) {
    const existing = await this.dictionaryRepository.findOne({ where: { type } });
    if (existing) {
      throw new Error('字典类型已存在');
    }
    return this.dictionaryRepository.save({ type, name,description });
  }

  async addDictionaryItem(type: string, key: string, value: string) {
    const dictionary = await this.dictionaryRepository.findOne({ where: { type } });
    if (!dictionary) {
      throw new Error('字典类型不存在');
    }
    return this.itemRepository.save({ key, value, dictionary });
  }

  async removeDictionaryItem(itemId: number) {
    const result = await this.itemRepository.delete(itemId);
    if (result.affected === 0) {
      throw new Error('字典项不存在');
    }
  }

  async getAllDictionaries(type: string) {
    return this.dictionaryRepository.find();
  }



  async getDictionaryByType(type: string) {
    const dictionary = await this.dictionaryRepository.findOne({
      where: { type },
      relations: ['items']
    });


    console.log('输出：',dictionary)
    if (!dictionary) {
      throw new Error('字典类型不存在');
    }
    return dictionary.items;
  }


  async updateDictionary(type: string, newName: string) {
    const dictionary = await this.dictionaryRepository.findOne({ where: { type } });
    if (!dictionary) {
      throw new Error('字典类型不存在');
    }
    dictionary.name = newName;
    return this.dictionaryRepository.save(dictionary);
  }

  async updateDictionaryItem(itemId: number, newKey: string, newValue: string) {
    const item = await this.itemRepository.findOne({ where: { id: itemId } });
    if (!item) {
      throw new Error('字典项不存在');
    }
    item.key = newKey;
    item.value = newValue;
    return this.itemRepository.save(item);
  }

  async deleteDictionary(type: string) {
    console.log('----------------------------',type)
    const dictionary = await this.dictionaryRepository.findOne({
      where: { type },
      relations: ['items']
    });
    console.log(dictionary)
    if (!dictionary) {
      // throw new Error('字典类型不存在');
      return {
        msg: "字典类型不存在"
        //throw new Error('存在关联字典项，无法删除');
      }
    }

    if (dictionary.items && dictionary.items.length > 0) {
      return {
        msg: "存在关联字典项，无法删除"
        //throw new Error('存在关联字典项，无法删除');
      }
    }
    return this.dictionaryRepository.delete(dictionary.id);
  }
}
